<?php

namespace app\api\controller\shop;

use app\common\controller\Api;
use think\Db;
use think\Exception;
use think\exception\ErrorException;
use think\Config;


/**
 * 合伙人小程序接口
 */
class Pshop extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = '*';

   
     /**
     * 服务商首页
     * 
     * 
     *  
     */
    public function shopindex()
    {
        $shop_id = $this->request->request('shop_id');
        $condi = [];
        $condi['user_id'] = $this->auth->id;
        $condi['status'] = 'normal';
        $investor_id = Db::name('investor_info')->where($condi)->value('id');

        if (!$investor_id) {
            $this->error(__('非法请求'));
        }

        //投资金额
        $condi = [];
        $condi['investor_id'] = $investor_id;
        $condi['shop_id'] = $shop_id;
        $investment = Db::name('investor_shop')->where($condi)->find();

        //收益统计
        $profit = Db::name('investor_profit')->where($condi)->find();

        $result = [];
        $result['investment'] = isset($investment['money'])?$investment['money']:0;
        $result['total_amount'] = isset($profit['total_amount'])?$profit['total_amount']:0;
        $result['available_amount'] = isset($profit['available_amount'])?$profit['available_amount']:0;
        $this->success('ok', $result);
        
    }


   
     /**
     * 门店列表
     * 
     * 
     *  @param string $keyword  店铺名称
     */
    public function shoplist()
    {
        //设置过滤方法
		$this->request->filter(['strip_tags']);
    	$keyword = $this->request->request('keyword'); 
        
        $condi = [];
        $condi['user_id'] = $this->auth->id;
        $condi['status'] = 'normal';
        $investor_id = Db::name('investor_info')->where($condi)->value('id');

        if (!$investor_id) {
            $this->error(__('非法请求'));
        }

        $shop_ids = Db::name('investor_shop')->where('investor_id',$investor_id)->column('shop_id');

        if(count($shop_ids) == 0){
            $this->error(__('无投资店铺列表'));
        }
        if ($keyword) {
        	$where['shopname'] = ['like', '%'.$keyword.'%'];   
        }
        $where['status'] = 'normal';

        $where['id'] = ['in',$shop_ids];

        $list = Db::name('wanlshop_shop')
                ->field('id,shopname,city,type,status,avatar')
                ->where($where)
                ->paginate();
        $this->success('ok', $list);
    }

    /**
     * 修改
     */
    public function editbankcard()
    {
        if ($this->request->isPost()) {
            //设置过滤方法
            $this->request->filter(['strip_tags']);
            $params = $this->request->post();
            $data = [];
            $data['bank_card_no'] = $params['bank_card_no'];
            $data['bank_name'] = $params['bank_name'];
            $data['bank_subbranch_name'] = $params['bank_subbranch_name'];
            $data['bank_username'] = $params['bank_username'];
            // $data['bank_mobile'] = $params['bank_mobile'];

            $condi = [];
            $condi['user_id'] = $this->auth->id;
            $condi['status'] = 'normal';
            $investor_id = Db::name('investor_info')->where($condi)->value('id');
            
            if (!$investor_id) {
                $this->error(__('非法请求'));
            }

            $res = Db::name('investor_info')->where('id',$investor_id)->update($data);

            $this->success('ok');

        } else {
            $this->error(__('非法请求'));
        }
    }

     public function operateday()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        $starttime = $this->request->request('starttime');
        $endtime = $this->request->request('endtime');
        $shop_id = $this->request->request('shop_id');
        $starttime = strtotime($starttime);
        $endtime = strtotime($endtime.' 23:59:59');

        /*** 总的实际收款 ***/
        $where = [];
        if ($starttime && $endtime) {
            $where['createtime'][] = ['>=',$starttime];
            $where['createtime'][] = ['<=',$endtime];
        }

        if ($shop_id != 1) {
            $where['shop_id'] = $shop_id;
        }

        $where['state'] = 6;

        $list = [];
        $result = Db::name('wanlshop_order')
            ->where($where)
            ->whereNull('deletetime')
            ->sum('actual_price');
        $list['data_1'] = is_null($result)? "0.00" : sprintf('%.2f',$result);

        $where = [];
        if ($starttime && $endtime) {
            $where['o.createtime'][] = ['>=',$starttime];
            $where['o.createtime'][] = ['<=',$endtime];
        }

        if ($shop_id != 1) {
            $where['o.shop_id'] = $shop_id;
        }

        $where['o.state'] = '6';
        $where['p.type'] = '2';

        $result = Db::name('wanlshop_order')->alias('o')
                  ->join('wanlshop_pay_out_trade t', 'o.id=t.order_id', 'left')
                  ->join('pay p', 'p.id=t.pay_way_id', 'left')
                  ->where($where)
                  ->sum('t.price');
        $list['data_8'] = is_null($result)? "0.00" : sprintf('%.2f',$result);


        /** 卡项消耗 **/

        $where2=[];
        $where2['o.data_type'] = ['<>','merchant'];
        if ($shop_id != 1) {
            $where2['o.shop_id'] = $shop_id;
        }
        $data_2 = Db::name('wanlshop_order')->alias('o')
            ->join('wanlshop_order_item_pay p', 'o.id=p.order_id', 'left')
            ->where('o.createtime', 'between time', [$starttime, $endtime])
            ->where($where2)
            ->where('o.state', 6)
            ->sum('p.money');
        $list['data_2'] =$data_2 ?? 0.00;
        /** 实际付款收入 **/
        $where = [];
        if ($starttime && $endtime) {
            $where['o.createtime'][] = ['>=',$starttime];
            $where['o.createtime'][] = ['<=',$endtime];
        }

        if ($shop_id != 1) {
            $where['o.shop_id'] = $shop_id;
        }

        $where['o.state'] = ['in',[2,3,4,5,6]];

        $sumpay = Db::name('wanlshop_order_item i')
            ->join('wanlshop_order o', 'o.id = i.order_id', 'LEFT')
            ->where($where)
            ->where(['i.type'=>['in',[1,2]]])
            ->sum('i.actual_price');
        //echo Db::name('wanlshop_order_item i')->getLastSql();exit;
        $list['data_3'] = is_null($sumpay)? 0.00 : sprintf('%.2f',$sumpay);


        /** 充值收入 **/
        //$where['i.type'] = 4;
        $sumpay = Db::name('wanlshop_order_item i')
            ->join('wanlshop_order o', 'o.id = i.order_id', 'LEFT')
            ->where($where)
            ->where(['i.type'=>['in',[4]]])
            ->sum('i.actual_price');

        $list['data_4'] = is_null($sumpay)? 0 : sprintf('%.2f',$sumpay);


        $where = [];
        if ($starttime && $endtime) {
            $where['o.createtime'][] = ['>=',$starttime];
            $where['o.createtime'][] = ['<=',$endtime];
        }
        if ($shop_id != 1) {
            $where['o.shop_id'] = $shop_id;
        }
        $where['o.state'] = ['in',[2,3,4,5,6]];

        $where['g.gdtype'] = '1';
        $sumpay = Db::name('wanlshop_order_goods g')
            ->join('wanlshop_order o', 'o.id = g.order_id', 'LEFT')
            ->where($where)
            ->sum('o.actual_price');
        $where2 = [];
        $where2['o.data_type'] = ['<>','merchant'];
        if ($shop_id != 1) {
            $where2['o.shop_id'] = $shop_id;
        }
        $sumpay = Db::name('wanlshop_order_goods')->alias('i')
                ->join('wanlshop_order o', 'o.id=i.order_id', 'left')
                ->join('wanlshop_pay_out_trade t', 'o.id=t.order_id', 'left')
                ->join('pay p', 'p.id=t.pay_way_id', 'left')
                ->where($where2)
                ->where('p.type','<>','1')
                ->where('o.createtime', 'between time', [$starttime, $endtime])
                ->field('sum(i.number * i.actual_payment ) as sum')
                ->where('o.state',  '6')
                ->where('i.gdtype',  '1')
                ->find();
        $list['data_5'] = isset($sumpay['sum'])? sprintf('%.2f',$sumpay['sum']) : '0.00';

        $where = [];
        $where['o.data_type'] = ['<>','merchant'];
        if ($shop_id != 1) {
            $where['o.shop_id'] = $shop_id;
        }
        $data_6 = Db::name('wanlshop_order_goods')->alias('i')
            ->join('wanlshop_order o', 'o.id=i.order_id', 'left')
            ->join('wanlshop_pay_out_trade t', 'o.id=t.order_id', 'left')
            ->join('pay p', 'p.id=t.pay_way_id', 'left')
            ->where($where)
            ->where('p.type','<>','1')
            ->where('o.createtime', 'between time', [$starttime, $endtime])
            ->field('sum(i.number * i.actual_payment ) as sum')
            ->where('o.state', '6')
            ->where('i.gdtype', '0')
            ->select();

        $list['data_6'] = isset($data_6['0']['sum']) ? $data_6['0']['sum'] : sprintf('%.2f',0);
        $where = [];
        if ($starttime && $endtime) {
            $where['createtime'][] = ['>=',$starttime];
            $where['createtime'][] = ['<=',$endtime];
        }
        if ($shop_id != 1) {
            $where['shop_id'] = $shop_id;
        }
        $where['state'] = ['in',[11]];
        $refund =Db::name('wanlshop_order')
            ->where($where)
            ->sum('actual_price');

        $list['data_7'] = $refund ?? 0.00; // 退款
        $list['data_7'] = sprintf('%.2f',$list['data_7']);

        $data_9 = 0;
        $condi = [];
        $condi['user_id'] = $this->auth->id;
        $condi['status'] = 'normal';
        $investor_id = Db::name('investor_info')->where($condi)->value('id');
        if (!empty($investor_id) && $investor_id != 0) {
            $where = [];
            $where['investor_id'] = $investor_id;
            $where['shop_id'] = $shop_id;
            if ($starttime && $endtime) {
                $where['createtime'][] = ['>=',$starttime];
                $where['createtime'][] = ['<=',$endtime];
            }
            $investor_money_log = Db::name('investor_money_log')->where($where)->select();
            if (count($investor_money_log) > 0) {
                foreach ($investor_money_log as $key => $value) {
                    if ($value['type'] == 0) {
                        $data_9 += $value['money'];
                    }
                }
            }
        }
        $list['data_9'] = sprintf('%.2f',$data_9);

        $this->success('ok', $list);

    }

    /**
     * 提现记录
     * 
     */
    public function withdrawlist()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        $shop_id = $this->request->request('shop_id',0);
        $page = $this->request->request('page',1);
        $page_size = $this->request->request('page_size',15);
        
        $where = [];
        $starttime = $this->request->request('starttime',date('Y-m-d'));
        $endtime = $this->request->request('endtime',date('Y-m-d'));
        if ($starttime && $endtime) {
            $starttime = strtotime($starttime);
            $endtime = strtotime("{$endtime} +1 day -1 second");
            $where['createtime'][] = ['>=',$starttime];
            $where['createtime'][] = ['<=',$endtime];
        }

        $condi = [];
        $condi['user_id'] = $this->auth->id;
        $condi['status'] = 'normal';
        $investor_id = Db::name('investor_info')->where($condi)->value('id');
        
        if (!$investor_id) {
            $this->error(__('非法请求'));
        }

        if ($shop_id != 0) {
            $where['shop_id'] = $shop_id;
        }
        
        $where['investor_id'] = $investor_id;
        $list = Db::name('investor_withdraw')
            ->where($where)
            ->field('id,money,createtime,status,memo')
            ->page($page,$page_size)
            ->order('createtime desc')
            ->select();

        $this->success('ok', $list);

    }

    /**
     * 申请提现
     *  
     */
    public function withdraw()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        $amount = floatval($this->request->request('amount',0));
        $shop_id = $this->request->request('shop_id',0);
        
        if ($amount == 0) {
            $this->error(__('提现金额不能为0'));
        }

        $condi = [];
        $condi['user_id'] = $this->auth->id;
        $condi['status'] = 'normal';
        $investor_info = Db::name('investor_info')->where($condi)->find();
        
        if (!$investor_info) {
            $this->error(__('合伙人信息不存在'));
        }

        $condi = [];
        $condi['investor_id'] = $investor_info['id'];
        $condi['shop_id'] = $shop_id;
        $investor_profit = Db::name('investor_profit')->where($condi)->find();

        if (!$investor_profit) {
            $this->error(__('合伙人收益信息不存在'));
        }

        if (empty($investor_info['bank_card_no']) || empty($investor_info['bank_name']) || empty($investor_info['bank_subbranch_name'])) {
            $this->error(__('请完善银行卡信息'),[],1001);
        }

        if ($amount > floatval($investor_profit['available_amount'])) {
            $this->error(__('可提现收益不足！'));
        }

        Db::startTrans();
        try{
            $data = [
                'investor_id' => $investor_info['id'],
                'shop_id' => $shop_id,
                'money' => $amount,
                'handingfee'=> 0,
                'memo'=>'提现至【'.$investor_info['bank_name'].substr($investor_info['bank_card_no'], -4).'】',
                'bank_card_no' => $investor_info['bank_card_no'],
                'createtime' => time(),
                'updatetime' => time(),
            ];

            $result = Db::name('investor_withdraw')->insert($data);

            if (!$result || empty($result)) {
                Db::rollback();
                $this->error('提现失败，请稍后重试');
            }

            $decResult = Db::name('investor_profit')
                ->where('id', $investor_profit['id'])
                ->update([
                    'available_amount' => Db::raw('available_amount - '.$amount),
                    'lock_amount' => Db::raw('lock_amount + '.$amount)
                ]);

            // 检查两个操作是否都成功
            if ($decResult == false) {
                throw new \Exception('提现失败');
            }
            
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            write_log_record("提现失败,失败原因：".json_encode($e));
            $this->error($e->getMessage());
        }

        $this->success('提现成功', []);
    }   
}
